package com.example.steriousfx.utils;

import cn.yeziji.http.tools.MRequest;
import cn.yeziji.utils.JsonUtils;
import cn.yeziji.utils.MD5Utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.HttpGet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 翻译工具类
 *
 * @author gzkemays
 * @since 2021/10/19 19:34
 */
public class TransitionUtils {
  private static final String BAI_DU_TRANSITION_API =
      "https://fanyi-api.baidu.com/api/trans/vip/translate?";
  private static final String DEFAULT_TRANSITION_FROM = "auto";
  private static final String DEFAULT_TRANSITION_TO = "zh";
  private static final String QUERY_PARAM = "q";
  private static final String FROM_PARAM = "from";
  private static final String TO_PARAM = "to";
  private static final String SALT_PARAM = "salt";
  private static final String SIGN_PARAM = "sign";
  private static final String TRANS_KEY = "trans_result";
  private static final String ERROR_CODE_KEY = "error_code";
  private static final String DST_KEY = "dst";
  private static final String FREQUENT_QUICK_CODE = "54003";

  private String appid;
  private String secret;
  private String query;
  private String to;
  private String from;
  Map<String, String> params = new HashMap<String, String>();

  {
    params.put(TO_PARAM, DEFAULT_TRANSITION_TO);
    params.put(FROM_PARAM, DEFAULT_TRANSITION_FROM);
  }

  public static TransitionUtils create(String appid, String secret) {
    TransitionUtils utils = new TransitionUtils();
    utils.appid = appid;
    utils.secret = secret;
    utils.params.put("appid", appid);
    return utils;
  }

  public TransitionUtils query(String query) {
    this.query = query;
    try {
      params.put(QUERY_PARAM, URLEncoder.encode(query, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return this;
  }

  public TransitionUtils from(String from) {
    this.from = from;
    params.put(FROM_PARAM, from);
    return this;
  }

  public TransitionUtils to(String to) {
    this.to = to;
    params.put(TO_PARAM, to);
    return this;
  }

  public String transition(String txt) {
    this.query = txt;
    try {
      params.put(QUERY_PARAM, URLEncoder.encode(txt, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return transition();
  }

  public String transition() {
    if (params.get(QUERY_PARAM) == null) {
      throw new IllegalArgumentException("缺乏查询参数");
    }
    HttpGet noDataGet = MRequest.getNoDataGet(builderUrl());
    try {
      String result = MRequest.getResultFromRequest(noDataGet);
      if (JsonUtils.isJson(result)) {
        JSONObject jsonResult = JSONObject.parseObject(result);
        boolean hasCode = jsonResult.get(ERROR_CODE_KEY) != null;
        // 如果频繁访问，会返回错误码，此处休眠 1.5s 后重试。
        if (hasCode && jsonResult.getString(ERROR_CODE_KEY).equals(FREQUENT_QUICK_CODE)) {
          Thread.sleep(1500);
          transition();
        }
        return jsonResult.getJSONArray(TRANS_KEY).getJSONObject(0).getString(DST_KEY);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 构建拼接 param url
   *
   * @return url 拼接结果
   */
  private String builderUrl() {
    if (params.isEmpty()) {
      return BAI_DU_TRANSITION_API;
    }
    StringJoiner sj = new StringJoiner("&", BAI_DU_TRANSITION_API, "");
    String salt = String.valueOf(System.currentTimeMillis());
    String sign = appid + query + salt + secret;
    params.put(SALT_PARAM, salt);
    // 构建签名
    params.put(SIGN_PARAM, MD5Utils.chineseMd5(sign));
    // 拼接参数
    for (Map.Entry<String, String> entry : params.entrySet()) {
      String value = entry.getValue();
      String key = entry.getKey();
      if (value == null) {
        continue;
      }
      sj.add(key + "=" + value);
    }
    return sj.toString();
  }

  public static void main(String[] args) {}
}
